import { KVAny } from "../type/kv";
// import { format } from 'date-fns';
import { format } from "date-fns";

/**
 * serialize kv object
 * @param object KVAny
 * @param delimiter string
 * @param lastDelimiter boolean, if true, tail delimiter will be keep
 */
export const serialize = (
  object: KVAny,
  delimiter = "&",
  lastDelimiter = false
): string => {
  let result = "";

  Object.entries(object).forEach(
    // entry => (result += entry[1] ? `${entry[0]}=${entry[1]}${delimiter}` : "")
  entry => (result += (entry[1] === undefined || entry[1] === null) ? "" : `${entry[0]}=${entry[1]}${delimiter}`)
  );

  if (result.length > 0 && !lastDelimiter) {
    result = result.substr(0, result.length - 1);
  }

  return result;
};

/**
 * deserialize str to kv object
 * @param str string
 * @param delimiter string
 */
export const deserialize = (str: string, delimiter = "&"): KVAny => {
  const result = {};
  const sections = str.split(delimiter);
  sections.forEach(section => {
    const pair = section.split("=");
    result[pair[1]] = pair[2];
  });

  return result;
};

export const dateFormat = (val: string) => {
  if (val) {
    return format(new Date(val), "yyyy-MM-dd HH:mm:ss");
  } else {
    return "";
  }
};

export const dateFormatHH = (val: string) => {
  if (val) {
    return format(new Date(val), "yyyy-MM-dd HH:mm");
  } else {
    return "";
  }
};
